package com.itc.bi.utils;

import com.itc.bi.utils.FilterComponent.FieldColumn;
import com.itc.bi.utils.FilterComponent.Node;
import io.netty.util.internal.ObjectUtil;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.List;

public class FilterExp {

    StringBuffer buffer = new StringBuffer();
    StringBuffer fieldBuffer = new StringBuffer();
    Node node;

    public FilterExp(Node node){
        this.node = node;
        if(null != node){
            expresse(this.node);
            if(fieldBuffer.length()>0){
                fieldBuffer.delete(fieldBuffer.length()-1,fieldBuffer.length());
            }
        }
    }

    public String exp(){
        return buffer.toString();
    }

    public String getFields(){
        return fieldBuffer.toString();
    }

    private int expresse(Node node){
        int type = 0;
        //子节点和字段都为空
        if(CollectionUtils.isEmpty(node.getFiedlList()) && CollectionUtils.isEmpty(node.getNodeList())){
            return type;
        }
        //先处理节点字段
        if(node.getFiedlList().size()>0){
            type++;
            List<FieldColumn> fiedlList = node.getFiedlList();
            for (int i = 0; i < fiedlList.size(); i++) {
                FieldColumn fieldColumn = fiedlList.get(i);
                if(i > 0){
                    buffer.append(" ").append(node.getOperator());
                }
                buffer.append(" ").append(fieldColumn.getExp());
                fieldBuffer.append(fieldColumn.getFieldName()).append("、");
            }
        }
        //子节点
        if(node.getNodeList().size()>0){
            List<Node> nodeList = node.getNodeList();
            for (int i = 0; i < nodeList.size(); i++) {
                int index = buffer.length();
                if(type == 1){
                    buffer.append(" ").append(node.getOperator());
                }
                int kuahaoIndex = buffer.length();
                int res = expresse(nodeList.get(i));
                if(0 == res){
                    buffer.delete(index,buffer.length());
                    return type;
                }else if(2 != res){
                    buffer.insert(kuahaoIndex," (");
                    buffer.append(")");
                }
            }
            type = type+2;
        }
        return type;
    }
}
